import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

public class SingleQueryThread implements Runnable {

	private String[] apiKey = { "c5004103a64815cbe42cb9bd439b4e20",
			"59caa212e3b574e6d80350b19cfcdd23",
			"4d1538f57aea146bfb76025d51bf760c" };
	private String queryURL;
	private String queryItem;
	private int numOfRes;
	private ArrayList<String> imgUrls;
	private boolean runnable;

	public SingleQueryThread(String q, int keyIndex) {
		queryItem = q;
		queryURL = "http://flickr.com/services/rest/?method=flickr.photos.search&api_key="
				+ apiKey[keyIndex] + "&tags=" + q + "&tag_mode=all&per_page=10";
		numOfRes = 0;
		imgUrls = new ArrayList<String>();
		runnable = true;
	}

	@Override
	public void run() {
		try {
			while (runnable) {
				URL url = new URL(queryURL);

				// make connection, use post mode, and send query
				URLConnection urlc = url.openConnection();
				urlc.setDoOutput(true);
				urlc.setAllowUserInteraction(false);

				// retrieve result (we're only interested in the total number
				// value)
				BufferedReader br = new BufferedReader(new InputStreamReader(
						urlc.getInputStream()));
				String numStr = null;

				String str;
				int i = 0;
				while ((str = br.readLine()) != null) {
					if (i == 2) {
						numStr = str.toString();
						// break if no results
						if (str.indexOf("/") != -1) {
							break;
						}
					}

					if ((i > 2) && (str.charAt(1) != '/')) {
						imgUrls.add(SingleQueryThread.imgURLConstructor(str));
					}

					if (i > 6)
						break;

					i++;
				}
				br.close();

				// pick out the total number value from the string
				int startIndex = numStr.indexOf("total") + 7;
				int endIndex = numStr.lastIndexOf("\"");
				setNumOfRes(Integer.parseInt(numStr.substring(startIndex,
						endIndex)));

				this.runnable = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public int getNumOfRes() {
		return this.numOfRes;
	}

	private void setNumOfRes(int resNum) {
		this.numOfRes = resNum;
	}

	public String getQueryItem() {
		return queryItem;
	}

	public ArrayList<String> getImgUrls() {
		return imgUrls;
	}

	/**
	 * This method is used to construct the image url from the xml file returned
	 * by FlickR API
	 *
	 * @param s
	 *            one line record containing the in the xml
	 * @return
	 */
	public static String imgURLConstructor(String s) {
		int startIndex, endIndex;

		// get farm number
		startIndex = s.indexOf("farm");
		endIndex = s.indexOf("title");
		String farm_id = s.substring(startIndex + 6, endIndex - 2);

		// get server number
		startIndex = s.indexOf("server");
		endIndex = s.indexOf("farm");
		String server_id = s.substring(startIndex + 8, endIndex - 2);

		// get id
		startIndex = s.indexOf("id");
		endIndex = s.indexOf("owner");
		String id = s.substring(startIndex + 4, endIndex - 2);

		// get secret number
		startIndex = s.indexOf("secret");
		endIndex = s.indexOf("server");
		String secret_id = s.substring(startIndex + 8, endIndex - 2);

		return "http://farm" + farm_id + ".staticflickr.com/" + server_id + "/"
				+ id + "_" + secret_id + ".jpg";
	}
}
